package de.lulusoft.anothertorrent.gui.commands;

import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.commands.IHandlerListener;

import de.lulusoft.anothertorrent.core.servers.Server;
import de.lulusoft.anothertorrent.gui.views.ConsoleView;

public class SendConsoleToServerCommand implements IHandler {
	
	public static final String ID = "de.lulusoft.anothertorrent.gui.commands.SendConsoleToServerCommand";
	public static final String P_COMMAND = "commandParameter";
	
	private Server server = null;
	
	public SendConsoleToServerCommand(Server server)
	{
		this.server = server;
	}

	@Override
	public void addHandlerListener(IHandlerListener handlerListener) {
		// TODO Auto-generated method stub
		System.out.println(handlerListener.toString());
	}

	@Override
	public void dispose() {
		// TODO Auto-generated method stub

	}

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {

		String rawCmds[] = event.getParameter(P_COMMAND).split(",");
		String cmd = rawCmds[0].trim();
		String params[] = new String[rawCmds.length - 1];
		for (int i = 1; i < rawCmds.length; i++)
		{
			params[i-1] = rawCmds[i].trim();
		}
		Object result = server.getRTorrentManager().getXmlrpcManager().sendCommand(cmd, params);
		String retval = "";
//		if (result instanceof Object[])
//		{
//			
//			for (Object r : ((Object[])result))
//			{
//				retval += r.toString() + "\n";
//			}
//		}
//		else 
//			retval = result.toString();
		retval = walkArray(result, 0);
		((ConsoleView)event.getTrigger()).appendServerText(retval);
		
		return null;
	}
	
	private String walkArray(Object obj, int level)
	{
		String retval = "";
		String tabs = "";
		for (int i= 0; i < level; i++)
			tabs += "\t";
		if (obj instanceof Object[])
		{
			
			retval = tabs + "[\n";
			for (Object o : (Object[])obj)
			{
				retval += walkArray(o, level+1);
			}
			retval += tabs + "]\n";
		}
		else
			retval = tabs + "\t" + obj.toString() + "\n";
		
		return retval;
	}

	@Override
	public boolean isEnabled() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean isHandled() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public void removeHandlerListener(IHandlerListener handlerListener) {
		// TODO Auto-generated method stub
		System.out.println(handlerListener.toString());
	}

}
